<template>
  <div class="container">
    <!-- 第一部分: 头部 -->
    <div class="header shadow">
      <div class="left-group">
      <el-button disabled type="primary">
        <el-icon><EditPen /></el-icon>
        <span style="vertical-align: middle"> 创建 </span>
      </el-button>
      <el-input placeholder="请输入内容" v-model="searchText" class="search-input" @input="handleInput">
        <template #append>
          <el-button type="primary"  @click="search()">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      </div>
      <div class="right-group">
      <el-button  @click="refresh">
        <el-icon><Refresh /></el-icon>
        <span> 刷新 </span>
      </el-button>
      </div>
    </div>

    <!-- 第二部分: 表格 -->
    <div class="table-wrapper shadow">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="nodeName" label="Node名" width="180" align="center">
          <template #default="{ row }">
            <div>
              <p style="color: #4795EE; margin: 0;">{{ row.nodeName }}</p>
              <p style="color: #aaa; margin: 0;">{{ row.hostName }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Specifications" label="规格" width="180" align="center">
          <template #default="{ row }">
            <div>
              <el-tag class="ml-2" type="success">{{row.Specifications}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="PodCIDR" label="POD-CIDR" align="center"></el-table-column>
        <el-table-column prop="version" label="版本" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template #default="{ row }">
            <div>
              <el-tag class="ml-2" type="warning">{{row.createTime}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Operation" label="操作" align="center">
          <template #default="{ row }">
            <el-button color="#5AABFF" :dark="isDark" plain @click="viewYAML(row)">
              <el-icon><EditPen /></el-icon>
              <span style="vertical-align: middle"> YAML </span>
            </el-button>
            <el-button color="#5AABFF" :dark="isDark" plain>
              <el-icon><Tickets /></el-icon>
              <span style="vertical-align: middle"> 详情 </span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 30]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total=nodeCount
          class="paginations"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="YAML信息" v-model="dialogVisible" width="45%" top="5%">
      <codemirror
          v-model="yamlContent"
          placeholder="请输入代码..."
          :style="{ height: '100%' }"
          v-bind="cmOptions"
          :extensions="extensions"
      />

      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button disabled type="primary" >更 新</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {nextTick, onBeforeMount, reactive, ref} from 'vue';
import {NAMESPACE_LIST, NODE_DETAIL_LIST, NODE_LIST} from "../../../api/k8s.js";
import { Codemirror } from "vue-codemirror";
import json2yaml from 'json2yaml'
import idea from "vue-codemirror"
import {javascript} from "@codemirror/lang-javascript";
import {oneDark} from "@codemirror/theme-one-dark";
import _ from "lodash";

const extensions = [javascript(),oneDark]
// import 'codemirror/mode/yaml/yaml.js'
// import 'codemirror/theme/idea.css'
let currentPage = ref(1)
let pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const isLoading = ref(true)
const dialogVisible = ref(false);
const currentYAMLContent = ref('');
let yamlContent = ref('');
//编辑器配置
const cmOptions = {
  // 语言及语法模式
  mode: 'text/yaml',
      // 主题
      theme: 'idea',
      // 显示行数
      lineNumbers: true,
      smartIndent: true, //智能缩进
      indentUnit: 4, // 智能缩进单元长度为 4 个空格
      styleActiveLine: true, // 显示选中行的样式
      matchBrackets: true, //每当光标位于匹配的方括号旁边时，都会使其高亮显示
      readOnly: false,
      lineWrapping: true //自动换行
}
const handleInput = _.debounce(async () => {
  await search();
}, 500); // 使用 lodash 的 debounce 函数来防抖，防止搜索操作太频繁
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  nodeParameters.page_size = val
  localStorage.setItem('nodepageSize', val); // 将页面大小保存在 localStorage

  getNodeData()
}
const onChange = (val)=> {
  yamlContent = val
}
// 转换Ki到G的函数
const kiToG = (ki) => {
  const kiValue = parseInt(ki.replace('Ki', '')); // 移除Ki并转换为整数
  return (kiValue / (1024 * 1024)).toFixed(2) + 'G'; // 转换为G并保留两位小数
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  localStorage.setItem('nodecurrentPage', val); // 将当前页保存在 localStorage

  nodeParameters.page_number = val
  getNodeData()
}
const viewYAML = (row) => {
  console.log('显示YAML信息', row);
  // 这里可以编写显示YAML信息的逻辑
  // 假设提供了 `getYAMLContent` 方法来获取 YAML 内容
  // 直接使用传入的 row 作为 YAML 内容
  getNodeDetailData(row.nodeName)
};

const viewDetails = (row) => {
  console.log('显示详情', row);
  // 这里可以编写显示详情信息的逻辑
};
const formatDateTime = (dateTimeString) => {
  return dateTimeString.replace('T', ' ').replace('Z', '');
};
// 示例数据和方法
const searchText = ref('');
const tableData = ref([
  {
    nodeName: '2016-05-02',
    Specifications: '王小虎',
    PodCIDR: '上海市普陀区金沙江路 1518 弄',
    version:"www",
    createTime:"2015",
    Operation:"555"
  },
  // ...其他数据项
]);

const search = async () => {
  console.log('执行搜索:', searchText.value);
  const searchParameters = reactive({
    page_size: pageSize,
    page_number: currentPage,
    filterName: searchText.value,
    isMaster: 3
  })
  try {
    const resp = await NODE_LIST(searchParameters)
    if (resp && resp.data && Array.isArray(resp.data.Items)) {
      tableData.value = resp.data.Items.map((item) => ({
        nodeName: item.metadata.name,
        hostName: item.metadata.labels['kubernetes.io/hostname'],
        Specifications: item.status.capacity.cpu + "核" + kiToG(item.status.capacity.memory),
        PodCIDR: item.spec.podCIDR,
        version: item.status.nodeInfo.kubeletVersion,
        createTime: formatDateTime(item.metadata.creationTimestamp),
        Operation: "hha",
        // 其他属性...
      }));
    }
    console.log(resp)
  }catch (e){
    console.log(e)
  }
};

const refresh = () => {
  console.log('刷新表格数据');
};

const nodeParameters = reactive({
  page_size: pageSize,
  page_number: currentPage,
  isMaster: 3,
})
var nodeCount = ref(0)
const getNodeData = async ()=>{
  try {
    const resp = await NODE_LIST(nodeParameters)
    if (resp && resp.data && Array.isArray(resp.data.Items)) {
      tableData.value = resp.data.Items.map((item) => ({
        nodeName: item.metadata.name,
        hostName: item.metadata.labels['kubernetes.io/hostname'],
        Specifications: item.status.capacity.cpu + "核" + kiToG(item.status.capacity.memory),
        PodCIDR: item.spec.podCIDR,
        version: item.status.nodeInfo.kubeletVersion,
        createTime: formatDateTime(item.metadata.creationTimestamp),
        Operation: "hha",
        // 其他属性...
      }));
    }
    nodeCount.value = resp.data.total

    console.log(resp)
    // for (const respKey of resp.data.Items) {
    //   console.log(respKey)
    //
    // }

  }catch (e){
    console.log(e)
  }
}
const getNodeDetailData = async (nodeName)=>{
  try {
    console.log(nodeName)
    const params = reactive({
      nodeName: nodeName,
    })
    const resp = await NODE_DETAIL_LIST(params)
    console.log("0000000000：",resp)

    console.log("yaml =======",json2yaml.stringify(resp.data))
    yamlContent.value = json2yaml.stringify(resp.data); // 确保将数据赋值给 yamlContent

    await  nextTick()
    dialogVisible.value = true;


  }catch (e){
    console.log(e)
  }
}
const getNodeAllData = async ()=>{
  const nodeAllParameters = reactive({
    page_size: 100000,
    page_number: 1,
    isMaster: 3,
  })
  try {
    const resp = await NODE_LIST(nodeAllParameters)
    console.log(resp)
    nodeCount.value = resp.data.total
    // for (const respKey of resp.data.Items) {
    //   console.log(respKey)
    //
    // }
  }catch (e){
    console.log(e)
  }
}
onBeforeMount( ()=> {
  const savedPageSize = localStorage.getItem('nodepageSize');
  const savedCurrentPage = localStorage.getItem('nodecurrentPage');

  if (savedPageSize && !isNaN(savedPageSize)) {
    pageSize.value = Number(savedPageSize);
  }

  if (savedCurrentPage && !isNaN(savedCurrentPage)) {
    currentPage.value = Number(savedCurrentPage);
  }
  getNodeData()

});
</script>

<style scoped>
.container {
  margin: 10px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 添加此属性对子元素进行分散对齐 */
  margin-bottom: 0px;
  gap: 10px;
  padding: 10px;
  background: #FFF;
  border: 2px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-input {
  /*flex-grow: 1;*/
  width: 200px;
}

.table-wrapper {
  background: #FFF;
  border: 2px solid #ebeef5; /* 浅色边框线 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.paginations {
  margin-top: 10px;
  margin-left: 20px;
  margin-bottom: 10px;
}
/* 左侧组合样式，创建按钮和搜索框靠在一起 */
.left-group {
  display: flex;
  align-items: center;
  gap: 10px; /* You can adjust the gap as needed */
}

/* 右侧刷新按钮 */
.right-group {
  display: flex;
  align-items: center;
}
.yaml-content {
  background-color: #f5f5f5;
  border-left: 3px solid #4795EE;
  padding: 15px;
  white-space: pre-wrap;
  text-align: left;
  margin: 20px 0;
  overflow-x: auto;
}

.dialog-footer {
  text-align: right;
}
</style>
